package com.zzzyh.bookbackgroundsystem.pojo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzzyh.bookbackgroundsystem.enums.ResponseCodeEnum;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Data
@Component
public class Response<T> {

    @Autowired
    private static ObjectMapper objectMapper;

    private ResponseCodeEnum code;
    private String message;
    private T data;


    // 无参构造函数
    public Response() {
    }

    // 带参数的构造函数
    public Response(ResponseCodeEnum code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }



    // 静态方法用于快速创建成功响应
    public static  <T> Response<T> success(T data) {
        return new Response<T>(ResponseCodeEnum.SUCCESS, "成功", data);
    }

    // 静态方法用于快速创建失败响应
    public static Response error(String message) {
        return new Response(ResponseCodeEnum.ERROR, message, null);
    }

    public static Response unknown( String message) {
        return new Response(ResponseCodeEnum.UNKNOWN, message, null);
    }

    // 重写 toString 方法，便于调试
    @Override
    public String toString() {
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
